/**
 * @file asteroid.c
 * @brief  spawn, move, update and init struct_enemy
 */

/* Allegro */
#include <allegro5/allegro5.h>
#include <allegro5/allegro_primitives.h>
#include <allegro5/altime.h>
#include <allegro5/display.h>
/* Stanrad */
#include <stdlib.h>
/* Project */
#include <asteroid.h>
#include <blasteroids.h>
#include <graphics.h>
#include <movement.h>

void asteroid_init(Asteroid *a) {
  srand(clock());
  ALLEGRO_DISPLAY *display = al_get_current_display();
  a->sx = rand() % al_get_display_width(display);
  a->sy = rand() % al_get_display_height(display);
  a->color = ASTR_COLOR;
  a->speed = ((double) rand() / ((double) RAND_MAX + 1) * ASTEROID_SPEED_MAX);
  a->twist = ((double) rand() / ((double) RAND_MAX + 1) * ASTEROID_TWIST_MAX);
  a->heading =
      ((double) rand() / ((double) RAND_MAX + 1) * ASTEROID_HEADING_MAX);
  a->scale = ((float) rand() / (float) RAND_MAX) + ASTEROID_SCALE_MIN;
  a->gone = rand() & 1;
  return;
}

void asteroid_check_pos(Asteroid *a) {
  ALLEGRO_DISPLAY *display = al_get_current_display();
  int width = al_get_display_width(display);
  int height = al_get_display_height(display);
  if (a->sx > width) {
    a->sx = 0;
  }
  if (a->sx < 0) {
    a->sx = width;
  }
  if (a->sy > height) {
    a->sy = 0;
  }
  if (a->sy < 0) {
    a->sy = height;
  }
}

void asteroids_init(Asteroid **as) {
  for (int i = 0; i < ASTEROIDS_MAX; i++) {
    as[i] = calloc(1, sizeof(Asteroid));
    asteroid_init(as[i]);
  }
}

void asteroids_update(Asteroid **as) {
  for (int i = 0; i < ASTEROIDS_MAX; i++) {
    if (as[i]->gone == 0) {
      continue;
    }
    asteroid_move(as[i], forward);
    asteroid_check_pos(as[i]);
    asteroid_draw(as[i]);
  }
}
void asteroids_free(Asteroid **as) {
  for (int i = 0; i < ASTEROIDS_MAX; i++) {
    free(as[i]);
  }
  free(as);
}

void asteroid_move(Asteroid *a, void (*direction)(float*, float*, float, float)) {
  direction(&a->sx, &a->sy, a->speed, a->heading);
}
